<template>
  <div class="sidebar" :class="{ collapsed: isCollapsed }">
    <div class="sidebar-header">
      <h2 class="sidebar-title">连接设置</h2>
      <button @click="toggleCollapse" class="collapse-btn">
        {{ isCollapsed ? '▶' : '◀' }}
      </button>
    </div>
    
    <div v-show="!isCollapsed">
      <ConnectionForm
        :connection="connection"
        :is-connected="isConnected"
        :connecting="connecting"
        @update-connection="onConnectionChange"
        @connect="connect"
        @disconnect="disconnect"
      />
      
      <IndicesSection
        :is-connected="isConnected"
        :indices="indices"
        :loading-indices="loadingIndices"
        :selected-index="selectedIndex"
        :refreshing="refreshing"
        @refresh-indices="refreshIndices"
        @select-index="selectIndex"
        @show-edit-index-modal="showEditIndexModal"
        @show-delete-index-modal="showDeleteIndexModal"
        @show-create-index-modal="showCreateIndexModal"
        @show-select-index-to-edit-modal="showSelectIndexToEditModal"
      />
    </div>
    
    <!-- 创建索引弹框 -->
    <CreateIndexModal
      v-if="showCreateIndexModalFlag"
      :is-connected="isConnected"
      @close="closeCreateIndexModal"
      @index-created="handleIndexCreated"
    />
    
    <!-- 编辑索引弹框 -->
    <EditIndexModal
      v-if="showEditIndexModalFlag"
      :index-name="indexToEdit"
      :is-connected="isConnected"
      @close="closeEditIndexModal"
      @index-updated="handleIndexUpdated"
    />
    
    <!-- 选择索引进行编辑弹框 -->
    <SelectIndexToEditModal
      v-if="showSelectIndexToEditModalFlag"
      :indices="indices"
      @close="closeSelectIndexToEditModal"
      @index-selected="handleIndexSelected"
    />
    
    <!-- 删除索引弹框 -->
    <DeleteIndexModal
      v-if="showDeleteIndexModalFlag"
      :indices="indices"
      :selected-indices="selectedIndicesForDeletion"
      :deleting-indices="deletingIndices"
      @close="closeDeleteIndexModal"
      @toggle-index-selection="toggleIndexSelection"
      @show-delete-confirm="showDeleteConfirm"
    />
    
    <!-- 删除确认弹框 -->
    <DeleteConfirmModal
      v-if="showDeleteConfirmFlag"
      :selected-indices="selectedIndicesForDeletion"
      :deleting-indices="deletingIndices"
      @close="closeDeleteConfirm"
      @delete-selected-indices="deleteSelectedIndices"
    />
  </div>
</template>

<script>
import ConnectionForm from './sidebar/ConnectionForm.vue';
import IndicesSection from './sidebar/IndicesSection.vue';
import CreateIndexModal from './sidebar/CreateIndexModal.vue';
import EditIndexModal from './sidebar/EditIndexModal.vue';
import SelectIndexToEditModal from './sidebar/SelectIndexToEditModal.vue';
import DeleteIndexModal from './sidebar/DeleteIndexModal.vue';
import DeleteConfirmModal from './sidebar/DeleteConfirmModal.vue';
import axios from 'axios';
import { API_BASE_URL } from '../api/config.js';
import '../styles/sidebar.css';

export default {
  name: 'Sidebar',
  components: {
    ConnectionForm,
    IndicesSection,
    CreateIndexModal,
    EditIndexModal,
    SelectIndexToEditModal,
    DeleteIndexModal,
    DeleteConfirmModal
  },
  props: {
    connection: {
      type: Object,
      required: true
    },
    isConnected: {
      type: Boolean,
      required: true
    },
    connecting: {
      type: Boolean,
      default: false
    },
    indices: {
      type: Array,
      default: () => []
    },
    loadingIndices: {
      type: Boolean,
      default: false
    },
    selectedIndex: {
      type: String,
      default: ''
    },
    refreshing: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isCollapsed: false,
      showCreateIndexModalFlag: false,
      showEditIndexModalFlag: false,
      showSelectIndexToEditModalFlag: false,
      indexToEdit: '',
      showDeleteIndexModalFlag: false,
      showDeleteConfirmFlag: false,
      selectedIndicesForDeletion: [],
      deletingIndices: false
    }
  },
  methods: {
    toggleCollapse() {
      this.isCollapsed = !this.isCollapsed;
    },
    connect(connection) {
      this.$emit('connect', connection);
    },
    disconnect() {
      this.$emit('disconnect');
    },
    refreshIndices() {
      this.$emit('refresh-indices');
    },
    selectIndex(index) {
      this.$emit('select-index', index);
    },
    onConnectionChange(connection) {
      this.$emit('update-connection', connection);
    },
    handleIndexCreated() {
      // 当索引创建成功后，刷新索引列表
      this.refreshIndices();
      // 关闭弹框
      this.showCreateIndexModalFlag = false;
    },
    showCreateIndexModal() {
      this.showCreateIndexModalFlag = true;
    },
    closeCreateIndexModal() {
      this.showCreateIndexModalFlag = false;
    },
    showEditIndexModal(indexName) {
      this.indexToEdit = indexName;
      this.showEditIndexModalFlag = true;
    },
    closeEditIndexModal() {
      this.showEditIndexModalFlag = false;
      this.indexToEdit = '';
    },
    handleIndexUpdated() {
      this.$emit('show-feedback', '索引更新成功', 'success');
      this.closeEditIndexModal();
      this.refreshIndices();
    },
    showSelectIndexToEditModal() {
      this.showSelectIndexToEditModalFlag = true;
    },
    closeSelectIndexToEditModal() {
      this.showSelectIndexToEditModalFlag = false;
    },
    handleIndexSelected(indexName) {
      this.showEditIndexModal(indexName);
    },
    showDeleteIndexModal() {
      this.showDeleteIndexModalFlag = true;
      this.selectedIndicesForDeletion = [];
    },
    closeDeleteIndexModal() {
      this.showDeleteIndexModalFlag = false;
      this.selectedIndicesForDeletion = [];
    },
    toggleIndexSelection(index) {
      const indexPos = this.selectedIndicesForDeletion.indexOf(index);
      if (indexPos === -1) {
        this.selectedIndicesForDeletion.push(index);
      } else {
        this.selectedIndicesForDeletion.splice(indexPos, 1);
      }
    },
    showDeleteConfirm() {
      if (this.selectedIndicesForDeletion.length > 0) {
        this.showDeleteConfirmFlag = true;
      }
    },
    closeDeleteConfirm() {
      this.showDeleteConfirmFlag = false;
    },
    async deleteSelectedIndices() {
      if (this.selectedIndicesForDeletion.length === 0) return;
      
      this.deletingIndices = true;
      try {
        const deletePromises = this.selectedIndicesForDeletion.map(indexName => 
          axios.delete(`${API_BASE_URL}/api/es/indices/${indexName}`)
        );
        
        const responses = await Promise.all(deletePromises);
        const successCount = responses.filter(response => response.data.success).length;
        const failCount = responses.length - successCount;
        
        if (failCount === 0) {
          this.$emit('show-feedback', `成功删除 ${successCount} 个索引`, 'success');
        } else {
          this.$emit('show-feedback', `删除了 ${successCount} 个索引，${failCount} 个索引删除失败`, 'error');
        }
        
        // 关闭确认框
        this.closeDeleteConfirm();
        this.closeDeleteIndexModal();
        // 刷新索引列表
        this.refreshIndices();
      } catch (error) {
        console.error('删除索引失败:', error);
        this.$emit('show-feedback', '删除索引失败: ' + (error.response?.data?.message || error.message), 'error');
      } finally {
        this.deletingIndices = false;
      }
    }
  }
}
</script>